package com.dhcc.cdc.busi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.CdcDictionaryMapper;
import com.dhcc.cdc.busi.dao.CdcDictypeMapper;
import com.dhcc.cdc.busi.dao.CdcOrdmastMapper;
import com.dhcc.cdc.busi.dao.CdcUserMapper;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcDictypeEntity;
import com.dhcc.cdc.busi.entity.CdcOrdmastEntity;
import com.dhcc.cdc.busi.entity.CdcUserEntity;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcOrdmastService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.cdc.sys.service.ICdcDataService;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 医嘱项表数据服务层接口
 * 
 * @ClassName: CdcOrdmastServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-03-15 10:20:07
 */
@Service("cdcOrdmastService")
public class CdcOrdmastServiceImpl extends BaseServiceImpl<CdcOrdmastMapper, CdcOrdmastEntity>
        implements ICdcOrdmastService {

    @Autowired
    ICdcDictionaryService dictritionSrv;
    @Autowired
    ICdcDataService dataSrv;
    
    @Autowired
    private CdcDictionaryMapper cdcDictionaryMapper;
	
	@Autowired
	private CdcDictypeMapper cdcDictypeMapper;
	
	@Autowired
	private CdcUserMapper cdcUserMapper;
	
	@Autowired
	private CdcDataMapper cdcDataMapper;

    @Override
    public List<CdcOrdmastEntity> page(Page<CdcOrdmastEntity> page, Map<String, Object> map) {
        return warpOrder(this.baseMapper.page(page, map));
    }

    @Override
    public List<CdcOrdmastEntity> list(Map<String, Object> map) {
        return this.baseMapper.list(map);
    }

    public List<CdcOrdmastEntity> warpOrder(List<CdcOrdmastEntity> list) {
        Map<Long, Object> cacheDic = new HashMap<Long, Object>();

        for (CdcOrdmastEntity order : list) {
            if (order.getBusOrderCateId() != null) {
                if (cacheDic.containsKey(order.getBusOrderCateId())) {
                    order.setBusOrderCate((CdcDictionaryEntity) cacheDic.get(order.getBusOrderCateId()));
                } else {
                    CdcDictionaryEntity orderCate = this.dictritionSrv.selectById(order.getBusOrderCateId());
                    order.setBusOrderCate(orderCate);
                    cacheDic.put(order.getBusOrderCateId(), orderCate);
                }
            } else {
                order.setBusOrderCate(new CdcDictionaryEntity());
            }

            if (order.getBusOrderSubcateId() != null) {
                if (cacheDic.containsKey(order.getBusOrderSubcateId())) {
                    order.setBusOrderSubcate((CdcDictionaryEntity) cacheDic.get(order.getBusOrderSubcateId()));
                } else {
                    CdcDictionaryEntity orderSubCate = this.dictritionSrv.selectById(order.getBusOrderSubcateId());
                    order.setBusOrderSubcate(orderSubCate);
                    cacheDic.put(order.getBusOrderSubcateId(), orderSubCate);
                }
            } else {
                order.setBusOrderSubcate(new CdcDictionaryEntity());
            }

            if (order.getBusOrderTypeId() != null) {
                if (cacheDic.containsKey(order.getBusOrderTypeId())) {
                    order.setBusOrderType((CdcDictionaryEntity) cacheDic.get(order.getBusOrderTypeId()));
                } else {
                    CdcDictionaryEntity orderType = this.dictritionSrv.selectById(order.getBusOrderTypeId());
                    order.setBusOrderType(orderType);
                    cacheDic.put(order.getBusOrderTypeId(), orderType);
                }
            } else {
                order.setBusOrderType(new CdcDictionaryEntity());
            }

            if (order.getDataId() != null) {
                if (cacheDic.containsKey(order.getDataId())) {
                    order.setData((CdcDataEntity) cacheDic.get(order.getDataId()));
                } else {
                    CdcDataEntity data = this.dataSrv.selectById(order.getDataId());
                    order.setData(data);
                    cacheDic.put(order.getDataId(), data);
                }
            } else {
                order.setData(new CdcDataEntity());
            }
        }

        return list;
    }

	@Override
	public String handleXmlData(String dataStr) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
        try {
            doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            Iterator<Element> iter = rootElt.elementIterator("location"); // 获取根节点下的子节点location
            // 遍历location节点
            while (iter.hasNext()) {
                Element orderEle = iter.next();
                String xcode= orderEle.elementTextTrim("xcode"); //唯一标识
                String code= orderEle.elementTextTrim("code"); //代码	
                String description= orderEle.elementTextTrim("description"); //描述
                String drugcommonname= orderEle.elementTextTrim("drugcommonname"); //药品通用名
                String chemcommonname= orderEle.elementTextTrim("chemcommonname"); //化学通用名
                String busordercatecode= orderEle.elementTextTrim("busordercatecode"); //大类代码	
                String busordercatedesc= orderEle.elementTextTrim("busordercatedesc"); //大类名称
                String busordersubcatecode= orderEle.elementTextTrim("busordersubcatecode"); //子类代码	
                String busordersubcatedesc= orderEle.elementTextTrim("busordersubcatedesc"); //子类名称
                String busordertypecode= orderEle.elementTextTrim("busordertypecode"); //类型代码
                String busordertypedesc= orderEle.elementTextTrim("busordertypedesc"); //类型名称
                String updatetimestr= orderEle.elementTextTrim("updatetime"); //更新时间
                String updateuserid= orderEle.elementTextTrim("updateuserid"); //更新人
                String opercode= orderEle.elementTextTrim("opercode"); //操作码
                CdcOrdmastEntity order = new CdcOrdmastEntity();
                order.setXcode(xcode);
                //获取basedataId
    			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
    			cdcDataEntityBase.setCode("HisBase");
    			cdcDataEntityBase.setIsActive(1);
    			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
        		Long basedataId = cdcDataEntityBase.getId();
        		//获取orddataId
    			CdcDataEntity cdcDataEntityOrd = new CdcDataEntity();
    			cdcDataEntityOrd.setCode("OrdData");
    			cdcDataEntityOrd.setIsActive(1);
    			cdcDataEntityOrd = cdcDataMapper.selectOne(cdcDataEntityOrd);
        		Long orddataId = cdcDataEntityOrd.getId();
        		if(CommonUtil.isNotEmpty(updatetimestr)) {
            		Date updatetime = sdf.parse(updatetimestr);
            		order.setUpdateDate(updatetime);
            	}
            	//获取更新人
            	if(CommonUtil.isNotEmpty(updateuserid)) {
            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
            		cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		cdcUserEntity.setIsActive(1);
            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
            		//判断人员存在不存在
            		Long updateuser = null;
            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
            			cdcUserEntity = new CdcUserEntity();
            			cdcUserEntity.setXcode(updateuserid);
                		cdcUserEntity.setIsActive(1);
            			cdcUserEntity.setCode("newuser"+updateuserid);
            			cdcUserEntity.setName("newuser"+updateuserid);
                		cdcUserEntity.setDataId(basedataId);
                		//保存用户
                		cdcUserMapper.insert(cdcUserEntity);
                		updateuser = cdcUserEntity.getId();
            		}else {
            			updateuser = cdcUserEntity.getId();
            		}
            		order.setUpdateBy(updateuser);
            	}
                if("1".equals(opercode)) {//保存/修改
                	
                	if(CommonUtil.isNotEmpty(code)) {
                		order.setCode(code);
                	}
                	if(CommonUtil.isNotEmpty(description)) {
                		order.setDescription(description);
                	}
                	if(CommonUtil.isNotEmpty(drugcommonname)) {
                		order.setDrugCommonName(drugcommonname);
                	}
                	if(CommonUtil.isNotEmpty(chemcommonname)) {
                		order.setChemCommonName(chemcommonname);
                	}
                	//获取ordercateId
                	if(CommonUtil.isNotEmpty(busordercatecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_order_cate");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicordercateId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicordercateId);
                		cdcDictionaryEntity.setCode(busordercatecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busordercateid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicordercateId);
                			cdcDictionaryEntity.setCode(busordercatecode);
                			cdcDictionaryEntity.setDescription(busordercatedesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busordercateid = cdcDictionaryEntity.getId();
                		}else {
                			busordercateid = cdcDictionaryEntity.getId();
                		}
                		order.setBusOrderCateId(busordercateid);
                	}
                	//获取ordersubcateId
                	if(CommonUtil.isNotEmpty(busordersubcatecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_order_subcate");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicordersubcateId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicordersubcateId);
                		cdcDictionaryEntity.setCode(busordersubcatecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busordersubcateid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicordersubcateId);
                			cdcDictionaryEntity.setCode(busordersubcatecode);
                			cdcDictionaryEntity.setDescription(busordersubcatedesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busordersubcateid = cdcDictionaryEntity.getId();
                		}else {
                			busordersubcateid = cdcDictionaryEntity.getId();
                		}
                		order.setBusOrderSubcateId(busordersubcateid);
                	}
                	//获取ordertypeId
                	if(CommonUtil.isNotEmpty(busordertypecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_order_type");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicordertypeId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicordertypeId);
                		cdcDictionaryEntity.setCode(busordertypecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busordertypeid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicordertypeId);
                			cdcDictionaryEntity.setCode(busordertypecode);
                			cdcDictionaryEntity.setDescription(busordertypedesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busordertypeid = cdcDictionaryEntity.getId();
                		}else {
                			busordertypeid = cdcDictionaryEntity.getId();
                		}
                		order.setBusOrderTypeId(busordertypeid);
                	}
                	order.setDataId(orddataId);
                	order.setIsActive(1);
                }else {
                	order.setIsActive(0);
                }
                //先判断是不是有该对象
                Wrapper<CdcOrdmastEntity> wrapper =  new EntityWrapper<CdcOrdmastEntity>();
                wrapper.eq("xcode", order.getXcode());
                wrapper.eq("data_id", orddataId);
                int count = this.selectCount(wrapper);
                if(count>0) {
                	this.update(order, wrapper);
                }else {
                	this.insert(order);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        } catch (Exception e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        }
		return "<response><status>1</status><message>ok</message></response>";
	}

}